package com.huatai.vba.controller;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.google.common.collect.Lists;
import com.huatai.vba.bean.BaseResp;
import com.huatai.vba.common.exception.BusinessException;
import com.huatai.vba.common.utils.BeanMapper;
import com.huatai.vba.dal.model.VbaFileAction;
import com.huatai.vba.service.VbaFileActionService;
import com.huatai.vba.vo.VbaFileActionVo;

@RestController
@RequestMapping(value = "action")
public class ActionController {

	private static final Logger logger = LoggerFactory.getLogger(ActionController.class);

	@Autowired
	private VbaFileActionService vbaFileActionService;

	@RequestMapping(value = "", method = RequestMethod.GET)
	public ModelAndView login() {
		ModelAndView mv = new ModelAndView("action");
		return mv;
	}

	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public List<VbaFileActionVo> list() {
		List<VbaFileActionVo> vos = null;
		try {
			List<VbaFileAction> list = vbaFileActionService.queryVbaFileAction((VbaFileAction) null);
			vos = Lists.newArrayList();
			for (VbaFileAction action : list) {
				VbaFileActionVo vo = BeanMapper.map(action, VbaFileActionVo.class);
				vo.setOperate("<a href=\"#\" onclick=\"javascript:execute(" + action.getActionId()
						+ ")\" class=\"btn btn-primary\">执行</a>");
				vos.add(vo);
			}
		} catch (BusinessException e) {
			vos = Lists.newArrayList();
		}
		return vos;
	}

	@RequestMapping(value = "/execute", method = RequestMethod.GET)
	@ResponseBody
	public BaseResp execute(@RequestParam(required = true) String actionId) {
		BaseResp resp = new BaseResp();
		try {
			boolean b = vbaFileActionService.executeAction(actionId, "system");
			resp.setSuccess(b);
		} catch (BusinessException e) {
			resp.setSuccess(false);
			resp.setMsg(e.getMessage());
		} catch (Exception e) {
			resp.setSuccess(false);
			resp.setMsg("系統異常");
		}
		return resp;
	}

}
